/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/ccjzxyxt">ccjzxyxt</a> All rights reserved.
 */
package cn.net.dckj.modules.biz.web;

import cn.net.dckj.common.config.Global;
import cn.net.dckj.common.persistence.Page;
import cn.net.dckj.common.utils.StringUtils;
import cn.net.dckj.common.utils.excel.ExportExcel;
import cn.net.dckj.common.utils.excel.ImportExcel;
import cn.net.dckj.common.web.BaseController;
import cn.net.dckj.modules.biz.common.EducationUtils;
import cn.net.dckj.modules.biz.entity.BizSchoolCalendar;
import cn.net.dckj.modules.biz.entity.BizTeacherTimetable;
import cn.net.dckj.modules.biz.entity.ClassTime;
import cn.net.dckj.modules.biz.service.BizSchoolCalendarService;
import cn.net.dckj.modules.biz.service.BizTeacherTimetableService;
import cn.net.dckj.modules.biz.service.ClassTimeService;
import cn.net.dckj.modules.sys.entity.User;
import cn.net.dckj.modules.sys.service.OfficeService;
import cn.net.dckj.modules.sys.service.SystemService;
import cn.net.dckj.modules.sys.utils.DictUtils;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 教师课表信息Controller
 *
 * @author xzy
 * @version 2019-04-15
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/bizTeacherTimetable")
public class BizTeacherTimetableController extends BaseController {

    @Autowired
    private BizTeacherTimetableService bizTeacherTimetableService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private ClassTimeService classTimeService;

    @Autowired
    private BizSchoolCalendarService bizSchoolCalendarService;

    @ModelAttribute("bizTeacherTimetable")
    public BizTeacherTimetable get(@RequestParam(required = false) String id) {
        BizTeacherTimetable entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = bizTeacherTimetableService.get(id);
        }
        if (entity == null) {
            entity = new BizTeacherTimetable();
        }
        return entity;
    }

    @RequiresPermissions("biz:bizTeacherTimetable:view")
    @RequestMapping(value = {"list", ""})
    public String list(BizTeacherTimetable bizTeacherTimetable, HttpServletRequest request, HttpServletResponse response, Model model) {
        String teacherId = bizTeacherTimetable.getTeacherId() == null ? "" : bizTeacherTimetable.getTeacherId();
        if (teacherId.length() > 2 && "u_".equals(teacherId.substring(0, 2))) {
            teacherId = teacherId.substring(2, teacherId.length());
            bizTeacherTimetable.setTeacherId(teacherId);
        }
        Page<BizTeacherTimetable> page = bizTeacherTimetableService.findPage(new Page<BizTeacherTimetable>(request, response), bizTeacherTimetable);
        model.addAttribute("page", page);
        return "modules/biz/bizTeacherTimetableList";
    }

    @RequiresPermissions("biz:bizTeacherTimetable:view")
    @RequestMapping(value = "form")
    public String form(BizTeacherTimetable bizTeacherTimetable, Model model) {
        String teacherId = bizTeacherTimetable.getTeacherId() == null ? "" : bizTeacherTimetable.getTeacherId();
        if (teacherId.length() > 2 && "u_".equals(teacherId.substring(0, 2))) {
            teacherId = teacherId.substring(2, teacherId.length());
            bizTeacherTimetable.setTeacherId(teacherId);
            User teacherUser = systemService.getUser(teacherId);
            bizTeacherTimetable.setTeacherName(teacherUser.getName());
        } else {
            if (StringUtils.isNotBlank(teacherId)) {
                // 重新查询是否选择节点是教师（前端控制，但有可能选择了组织机构节点）
                User teacherUser = systemService.getUser(teacherId);
                if (StringUtils.isNotBlank(teacherUser.getId())) {
                    bizTeacherTimetable.setTeacherName(teacherUser.getName());
                }
            }
        }
        /*User user = new User();
        user.setUserType("2");
        List<User> userlist = systemService.findUser(user);
        model.addAttribute("userlist", userlist);*/
        model.addAttribute("bizTeacherTimetable", bizTeacherTimetable);
        return "modules/biz/bizTeacherTimetableForm";
    }

    @RequiresPermissions("biz:bizTeacherTimetable:edit")
    @RequestMapping(value = "save")
    public String save(BizTeacherTimetable bizTeacherTimetable, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, bizTeacherTimetable)) {
            return form(bizTeacherTimetable, model);
        }
        /*if(StringUtils.isNotEmpty(bizTeacherTimetable.getClassId())){
            Office office = officeService.get(bizTeacherTimetable.getClassId());
			if(office==null){
				bizTeacherTimetable.setClassName("");
			}else{
				bizTeacherTimetable.setClassName(office.getName());
			}
		}*/
        // 判断校历是否存在，不存在保存失败
        String schoolYear = bizTeacherTimetable.getSchoolYear();
        if (StringUtils.isBlank(schoolYear)) {
            addMessage(redirectAttributes, "保存教师课表信息失败，原因：学年信息为空！");
            return "redirect:" + Global.getAdminPath() + "/biz/bizTeacherTimetable/?repage";
        }
        BizSchoolCalendar bizSchoolCalendar = bizSchoolCalendarService.getSchoolCalendar(schoolYear);
        if (bizSchoolCalendar == null) {
            addMessage(redirectAttributes, "保存教师课表信息失败，原因：未查询到校历信息！");
            return "redirect:" + Global.getAdminPath() + "/biz/bizTeacherTimetable/?repage";
        }
        // 判断修改or新增
        String teacherTimetableId = bizTeacherTimetable.getId();
        if (StringUtils.isNotBlank(teacherTimetableId)) {
            // 修改状态，判断修改字段是否影响课程时间
            BizTeacherTimetable oldEntity = bizTeacherTimetableService.get(teacherTimetableId);
            if (!oldEntity.getSchoolYear().equals(bizTeacherTimetable.getSchoolYear()) ||
                    !oldEntity.getTerm().equals(bizTeacherTimetable.getTerm()) ||
                    !oldEntity.getWeekStart().equals(bizTeacherTimetable.getWeekStart()) ||
                    !oldEntity.getWeekEnd().equals(bizTeacherTimetable.getWeekEnd()) ||
                    !oldEntity.getSection().equals(bizTeacherTimetable.getSection()) ||
                    !oldEntity.getWeekday().equals(bizTeacherTimetable.getWeekday())
                    ) {
                // 新增上课时间
                AddClassTime(bizSchoolCalendar, bizTeacherTimetable);
            }
            bizTeacherTimetableService.save(bizTeacherTimetable);
        } else {
            bizTeacherTimetableService.save(bizTeacherTimetable);
            // 新增上课时间
            AddClassTime(bizSchoolCalendar, bizTeacherTimetable);
        }
        addMessage(redirectAttributes, "保存教师课表信息成功");
        return "redirect:" + Global.getAdminPath() + "/biz/bizTeacherTimetable/?repage";
    }

    @RequiresPermissions("biz:bizTeacherTimetable:edit")
    @RequestMapping(value = "delete")
    public String delete(BizTeacherTimetable bizTeacherTimetable, RedirectAttributes redirectAttributes) {
        bizTeacherTimetableService.delete(bizTeacherTimetable);
        addMessage(redirectAttributes, "删除教师课表信息成功");
        return "redirect:" + Global.getAdminPath() + "/biz/bizTeacherTimetable/?repage";
    }

    /**
     * 下载导入教师课表数据模板
     *
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("biz:bizTeacherTimetable:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "教师课表数据导入模板.xlsx";
            List<BizTeacherTimetable> list = Lists.newArrayList();
            BizTeacherTimetable bizTeacherTimetable = new BizTeacherTimetable();
            bizTeacherTimetable.setSchoolYear("2019");
            bizTeacherTimetable.setTerm("1");
            bizTeacherTimetable.setWeekStart("1");
            bizTeacherTimetable.setWeekEnd("23");
            bizTeacherTimetable.setWeekday("1");
            bizTeacherTimetable.setSection("4");
            bizTeacherTimetable.setCourseName("钢结构施工技术");
            bizTeacherTimetable.setTeacherId("220102xxxx0808xxxx");
            bizTeacherTimetable.setTeacherName("教师姓名");
            bizTeacherTimetable.setClassName("班级名称1,班级名称2");
            bizTeacherTimetable.setAddress("DX511");
            bizTeacherTimetable.setRemarks("备注信息");
            list.add(bizTeacherTimetable);
            new ExportExcel("教师课表数据", BizTeacherTimetable.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/biz/bizTeacherTimetable/list?repage";
    }

    /**
     * 导入教师课表数据
     *
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("biz:bizTeacherTimetable:edit")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, BizTeacherTimetable bizTeacherTimetable, RedirectAttributes redirectAttributes) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/biz/bizTeacherTimetable/list?repage";
        }
        try {
            // 获取教师信息
            String teacherId = bizTeacherTimetable.getTeacherId() == null ? "" : bizTeacherTimetable.getTeacherId();
            if (teacherId.length() < 3 || !"u_".equals(teacherId.substring(0, 2))) {
                addMessage(redirectAttributes, "选择了无效的教师，课表导入失败！");
                return "redirect:" + adminPath + "/biz/bizTeacherTimetable/list?repage";
            }
            teacherId = teacherId.substring(2, teacherId.length());
            bizTeacherTimetable.setTeacherId(teacherId);
            User teacherUser = systemService.getUser(teacherId);
            String teacherName = teacherUser.getName();
            bizTeacherTimetable.setTeacherName(teacherName);

            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<BizTeacherTimetable> list = ei.getDataList(BizTeacherTimetable.class);
            for (BizTeacherTimetable entity : list) {
                try {
                    if (StringUtils.isBlank(entity.getSchoolYear())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：学年为空");
//                        break;
                    }
                    if (StringUtils.isBlank(entity.getTerm())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：学期为空");
//                        break;
                    }
                    if (StringUtils.isBlank(entity.getWeekStart())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：学周开始为空");
//                        break;
                    }
                    if (StringUtils.isBlank(entity.getWeekEnd())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：学周结束为空");
//                        break;
                    }
                    if (StringUtils.isBlank(entity.getWeekday())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：星期几为空");
//                        break;
                    }

                    if (StringUtils.isBlank(entity.getSection())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：课节为空");
//                        break;
                    }
                    if (StringUtils.isBlank(entity.getCourseName())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：课程名称为空");
//                        break;
                    }
                    if (StringUtils.isBlank(entity.getClassName())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：上课班级为空");
//                        break;
                    }
                    if (StringUtils.isBlank(entity.getAddress())) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：上课地址为空");
//                        break;
                    }
                    // 判断校历是否存在
                    BizSchoolCalendar bizSchoolCalendar = bizSchoolCalendarService.getSchoolCalendar(entity.getSchoolYear());
                    if (bizSchoolCalendar == null) {
                        failureNum++;
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：未设置校历信息");
//                        break;
                    }
                } catch (Exception ex) {
                    failureNum++;
                    failureMsg.append("<br/>课表 " + bizTeacherTimetable.getCourseName() + " 导入失败：" + ex.getMessage());
//                    break;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "课表导入失败，共" + failureNum + "处信息出错，原因如下：");
                addMessage(redirectAttributes, failureMsg.toString());
                return "redirect:" + adminPath + "/biz/bizTeacherTimetable/list?repage";
            } else {
                for (BizTeacherTimetable entity : list) {
                    try {
                        entity.setTeacherId(teacherId);
                        entity.setTeacherName(teacherName);
                        bizTeacherTimetableService.save(entity);
                        BizSchoolCalendar bizSchoolCalendar = bizSchoolCalendarService.getSchoolCalendar(entity.getSchoolYear());
                        // 新增上课时间
                        AddClassTime(bizSchoolCalendar, entity);
                        successNum++;
                    } catch (Exception e) {
                        failureMsg.append("<br/>课表 " + entity.getCourseName() + " 导入失败：" + e.getMessage());
                        failureNum++;
                    }
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条数据，导入信息如下：");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条数据" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入数据失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/biz/bizTeacherTimetable/list?repage";
    }

    @RequiresPermissions("biz:bizTeacherTimetable:view")
    @RequestMapping(value = {"index"})
    public String index(BizTeacherTimetable bizTeacherTimetable, Model model) {
        return "modules/biz/bizTeacherTimetableIndex";
    }

    // 新增上课时间
    private void AddClassTime(BizSchoolCalendar bizSchoolCalendar, BizTeacherTimetable bizTeacherTimetable) {
        // 删除原有上课时间
        classTimeService.deleteAll(bizTeacherTimetable.getId());
        ClassTime delClassTime = new ClassTime();
        delClassTime.setTeacherTimetableId(bizTeacherTimetable.getId());
        // 换成新写方法
//        classTimeService.delete(delClassTime);
        // 根据课节，换算上课开始和结束时间
        String section = bizTeacherTimetable.getSection();
        String startTime;   //上课开始时间
        String endTime;     //上课结束时间
        String time = DictUtils.getDictEntity("section", section).getRemarks();
        if (StringUtils.isNotEmpty(time)) {
            String[] strs = time.split("-");
            startTime = strs[0];
            endTime = strs[1];
        } else {
            if ("1".equals(section)) {
                startTime = "08:25:00";
                endTime = "09:50:00";
            } else if ("2".equals(section)) {
                startTime = "10:10:00";
                endTime = "11:35:00";
            } else if ("3".equals(section)) {
                startTime = "13:15:00";
                endTime = "14:40:00";
            } else {
                startTime = "15:00:00";
                endTime = "16:25:00";
            }
        }
        // 确定学期开始时间
        Date termStart;
        String term = bizTeacherTimetable.getTerm();
        if ("1".equals(term)) {
            termStart = bizSchoolCalendar.getFirstClassStartDate();
        } else {
            termStart = bizSchoolCalendar.getSecondClassStartDate();
        }
        int weekStart = Integer.parseInt(bizTeacherTimetable.getWeekStart());
        int weekEnd = Integer.parseInt(bizTeacherTimetable.getWeekEnd());
        // 上课星期几
        int weekday = Integer.parseInt(bizTeacherTimetable.getWeekday() == null ? "7" : bizTeacherTimetable.getWeekday());
        // 合成真正上课开始和结束时间并保存
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = weekStart; i <= weekEnd; i++) {
            ClassTime classTime = new ClassTime();
            classTime.setTeacherTimetableId(bizTeacherTimetable.getId());
            // 获取上课日期
            Date date = EducationUtils.getCourseDate(termStart, i, weekday);
            String dateStr = sdf.format(date);
            try {
                classTime.setCourseStartTime(format.parse(dateStr + " " + startTime));
                classTime.setCourseEndTime(format.parse(dateStr + " " + endTime));
                classTimeService.save(classTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
